<?php
/**
 * 蜘蛛监控插件 - 本地客户端许可证管理
 * 作者：Eric
 * 网站：https://zibovip.top
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * 订阅客户端类
 */
if (!class_exists('Spider_Subscription_Client')) {
class Spider_Subscription_Client {
    // 固定远程授权服务端基础地址（客户端硬编码）
    private $api_base_url = 'https://zibovip.top';
    private $debug = false;
    
    public function __construct() {
        // 可以在这里设置调试模式
        $this->debug = defined('WP_DEBUG') && WP_DEBUG;
        // 客户端使用固定的远程服务端地址，不依赖本地配置
        $this->api_base_url = 'https://zibovip.top';
    }
    
    /**
     * 检查许可证是否已激活
     */
    public function is_activated() {
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            return false;
        }
        
        // 检查缓存，避免频繁请求远程服务器
        $cache_key = 'spider_license_verification_' . md5($license_key);
        $cached_result = get_transient($cache_key);
        
        // 如果缓存存在且未过期（5分钟），使用缓存结果
        if ($cached_result !== false) {
            return $cached_result['is_active'] === true;
        }
        
        // 确保有服务端公钥
        if (!get_option('spider_server_public_key')) {
            $this->fetch_server_public_key();
        }
        
        // 强制向远程服务端验证
        $domain = home_url();
        $verification_result = $this->verify_license();
        
        if (!$verification_result || !$verification_result['success']) {
            // 验证失败，缓存失败结果（1分钟）
            set_transient($cache_key, ['is_active' => false], 60);
            return false;
        }
        
        // 只有远程服务端返回成功且状态为active才认为已激活
        $is_active = ($verification_result['status'] ?? '') === 'active';
        
        // 如果服务端返回的不是active状态，记录详细信息用于调试
        if (!$is_active) {
            if ($this->debug) {
                error_log('[SpiderMonitor] License verification failed - Status: ' . ($verification_result['status'] ?? 'unknown') . ', Message: ' . ($verification_result['message'] ?? 'no message'));
            }
        }
        
        // 缓存结果（成功5分钟，失败1分钟）
        $cache_duration = $is_active ? 300 : 60;
        set_transient($cache_key, ['is_active' => $is_active], $cache_duration);
        
        // 同步到安全模块
        if (function_exists('wp_spider_premium_security')) {
            $security = wp_spider_premium_security();
            if ($is_active) {
                $security->set_premium_status(true, $verification_result['expires_at'] ?? null);
            } else {
                $security->set_premium_status(false, null);
            }
        }
        
        return $is_active;
    }
    
    /**
     * 激活许可证
     */
    public function activate_license($license_key) {
        // 首先验证许可证密钥格式
        if (!$this->validate_license_key_format($license_key)) {
            return ['success' => false, 'message' => '许可证密钥格式无效，应为 XXXXX-XXXXX-XXXXX-XXXXX-XXXXX 格式'];
        }
        
        $domain = home_url();
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $wp_version = get_bloginfo('version');
        $plugin_version = defined('WP_SPIDER_MONITOR_VERSION') ? WP_SPIDER_MONITOR_VERSION : '2.0.0';
        
        $data = [
            'license_key' => $license_key,
            'domain' => $domain,
            'ip' => $ip_address,
            'user_agent' => $user_agent,
            'wp_version' => $wp_version,
            'plugin_version' => $plugin_version
        ];
        
        // 必须连接服务端进行验证
        $response = $this->make_api_request('activate', $data);
        
        // 强化验证：必须收到远程服务端的有效响应
        if (!$response) {
            return ['success' => false, 'message' => '无法连接到远程授权服务器'];
        }
        
        if (!is_array($response)) {
            return ['success' => false, 'message' => '远程服务器返回格式错误'];
        }
        
        if (!isset($response['success'])) {
            return ['success' => false, 'message' => '远程服务器响应缺少必要字段'];
        }
        
        if (!$response['success']) {
            return $response; // 返回服务器返回的错误信息
        }
        
        // 只有远程服务端明确返回成功时才保存激活信息
        update_option('spider_license_key', $license_key);
        $activation_data = [
            'is_active' => true,
            'license_key' => $license_key,
            'domain' => $domain,
            'plan' => $response['plan'] ?? 'basic',
            'expires_at' => $response['expires_at'] ?? date('Y-m-d', strtotime('+1 year')),
            'features' => $response['features'] ?? [],
            'activated_at' => current_time('mysql'),
            'last_remote_check' => current_time('mysql'),
            'server_status' => $response['status'] ?? 'unknown'
        ];
        update_option('spider_license_activation', $activation_data);
        
        // 清除验证缓存，确保下次检查时重新验证
        $this->clear_verification_cache($license_key);
        
        // 强制清除所有相关缓存
        delete_transient('spider_license_verification_' . md5($license_key));

        // 激活成功后，获取服务端公钥
        $this->fetch_server_public_key();

        // 激活成功后，立即刷新并保存客户端访问令牌（与远程短期令牌保持一致）
        if (file_exists(plugin_dir_path(__FILE__) . 'includes/remote-auth.php')) {
            require_once plugin_dir_path(__FILE__) . 'includes/remote-auth.php';
        } else if (file_exists(dirname(__FILE__) . '/includes/remote-auth.php')) {
            require_once dirname(__FILE__) . '/includes/remote-auth.php';
        }
        if (class_exists('WP_Spider_Remote_Auth')) {
            $refresh = \WP_Spider_Remote_Auth::refresh_token_now('general', 'general');
            if (is_array($refresh) && empty($refresh['success']) && $this->debug) {
                error_log('[SpiderMonitor] Token refresh after activation failed: ' . ($refresh['message'] ?? 'unknown'));
            }
        }
        
        // 同步到安全模块
        if (function_exists('wp_spider_premium_security')) {
            $security = wp_spider_premium_security();
            $security->set_premium_status(true, $activation_data['expires_at']);
            // 立即触发一次验证并缓存激活状态，避免页面还显示未激活
            set_transient('spider_license_verification_' . md5($license_key), ['is_active' => true], 300);
        }
        
        return $response;
    }
    
    
    /**
     * 停用许可证
     */
    public function deactivate_license() {
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            return ['success' => false, 'message' => '没有激活的许可证'];
        }
        
        $domain = home_url();
        $data = [
            'license_key' => $license_key,
            'domain' => $domain
        ];
        
        // 必须连接服务端进行验证
        $response = $this->make_api_request('deactivate', $data);
        
        // 强化验证：必须收到远程服务端的有效响应
        if (!$response) {
            return ['success' => false, 'message' => '无法连接到远程授权服务器'];
        }
        
        if (!is_array($response)) {
            return ['success' => false, 'message' => '远程服务器返回格式错误'];
        }
        
        if (!isset($response['success'])) {
            return ['success' => false, 'message' => '远程服务器响应缺少必要字段'];
        }
        
        if (!$response['success']) {
            return $response; // 返回服务器返回的错误信息
        }
        
        // 只有远程服务端明确返回成功时才清除本地激活信息
        delete_option('spider_license_key');
        delete_option('spider_license_activation');
        
        // 清除验证缓存
        $this->clear_verification_cache($license_key);

        // 停用后，失效本地访问令牌
        if (file_exists(plugin_dir_path(__FILE__) . 'includes/remote-auth.php')) {
            require_once plugin_dir_path(__FILE__) . 'includes/remote-auth.php';
        } else if (file_exists(dirname(__FILE__) . '/includes/remote-auth.php')) {
            require_once dirname(__FILE__) . '/includes/remote-auth.php';
        }
        if (class_exists('WP_Spider_Remote_Auth')) {
            \WP_Spider_Remote_Auth::invalidate_token();
        }
        
        // 同步到安全模块
        if (function_exists('wp_spider_premium_security')) {
            $security = wp_spider_premium_security();
            $security->set_premium_status(false);
        }
        
        return $response;
    }
    
    /**
     * 验证许可证
     */
    public function verify_license() {
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            return ['success' => false, 'message' => '没有激活的许可证'];
        }
        
        // 验证许可证密钥格式
        if (!$this->validate_license_key_format($license_key)) {
            return ['success' => false, 'message' => '许可证密钥格式无效'];
        }
        
        $domain = home_url();
        $data = [
            'license_key' => $license_key,
            'domain' => $domain
        ];
        
        $response = $this->make_api_request('verify', $data);
        
        // 强化验证：必须收到远程服务端的有效响应
        if (!$response) {
            return ['success' => false, 'message' => '无法连接到远程授权服务器'];
        }
        
        if (!is_array($response)) {
            return ['success' => false, 'message' => '远程服务器返回格式错误'];
        }
        
        if (!isset($response['success'])) {
            return ['success' => false, 'message' => '远程服务器响应缺少必要字段'];
        }
        
        if (!$response['success']) {
            return $response; // 返回服务器返回的错误信息
        }
        
        // 只有远程服务端明确返回成功时才更新本地数据
        $is_active = ($response['status'] ?? '') === 'active';
        $activation_data = [
            'is_active' => $is_active,
            'license_key' => $license_key,
            'domain' => $domain,
            'expires_at' => $response['expires_at'] ?? date('Y-m-d', strtotime('+1 year')),
            'features' => $response['features'] ?? [],
            'last_check' => current_time('mysql'),
            'last_remote_check' => current_time('mysql'),
            'server_status' => $response['status'] ?? 'unknown',
            'server_message' => $response['message'] ?? ''
        ];
        update_option('spider_license_activation', $activation_data);
        
        // 同步到安全模块
        if (function_exists('wp_spider_premium_security')) {
            $security = wp_spider_premium_security();
            $security->set_premium_status($activation_data['is_active'], $activation_data['expires_at']);
        }
        
        return $response;
    }
    
    
    /**
     * 获取许可证信息
     */
    public function get_license_info() {
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            return ['success' => false, 'message' => '没有激活的许可证'];
        }
        
        // 向远程服务器获取最新的许可证信息
        $domain = home_url();
        $data = [
            'license_key' => $license_key,
            'domain' => $domain
        ];
        
        $response = $this->make_api_request('verify', $data);
        
        if (!$response || !is_array($response)) {
            return ['success' => false, 'message' => '无法连接到远程服务器'];
        }
        
        return $response;
    }
    
    /**
     * 获取当前套餐
     */
    public function get_current_plan() {
        $license_info = $this->get_license_info();
        return $license_info['plan'] ?? 'basic';
    }
    
    /**
     * 获取可用功能
     */
    public function get_available_features() {
        $license_info = $this->get_license_info();
        return $license_info['features'] ?? [];
    }
    
    /**
     * 获取当前域名
     */
    public function get_domain() {
        return home_url();
    }
    
    /**
     * 获取许可证状态
     */
    public function get_license_status() {
        if (!$this->is_activated()) {
            return 'inactive';
        }
        
        $license_info = $this->get_license_info();
        if (isset($license_info['expires_at'])) {
            $expires_at = strtotime($license_info['expires_at']);
            if ($expires_at < current_time('timestamp')) {
                return 'expired';
            }
        }
        
        return 'active';
    }
    
    /**
     * 获取许可证到期时间
     */
    public function get_expires_at() {
        $license_info = $this->get_license_info();
        return $license_info['expires_at'] ?? null;
    }
    
    /**
     * 获取激活时间
     */
    public function get_activated_at() {
        $license_info = $this->get_license_info();
        return $license_info['activated_at'] ?? null;
    }
    
    /**
     * 发送API请求
     */
    private function make_api_request($endpoint, $data) {
        // 使用远程授权服务端API（可配置基础地址）
        $url = $this->api_base_url . '/dingyue/license-api.php?action=' . $endpoint;
        
        // 添加时间戳和随机数（可选的安全增强）
        $data['ts'] = time();
        $data['nonce'] = wp_generate_password(8, false);
        
        $args = [
            'method' => 'POST',
            'timeout' => 30,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Accept' => 'application/json, */*;q=0.1',
                'User-Agent' => 'Spider-Monitor-Client/' . (defined('WP_SPIDER_MONITOR_VERSION') ? WP_SPIDER_MONITOR_VERSION : '2.0.0')
            ],
            'body' => http_build_query($data)
        ];
        
        if ($this->debug) {
            error_log('Spider License API Request: ' . $url . ' - ' . http_build_query($data));
        }
        
        $response = wp_remote_post($url, $args);
        
        if (is_wp_error($response)) {
            if ($this->debug) {
                error_log('Spider License API Error: ' . $response->get_error_message());
            }
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body, true);
        
        if ($this->debug) {
            error_log('Spider License API Response: ' . $body);
        }
        
        return $result;
    }
    
    /**
     * 检查功能访问权限
     */
    public function check_feature_access($feature) {
        // 允许所有功能访问，但在前端显示PRO提示
        return true;
    }
    
    /**
     * 测试连接
     */
    public function test_connection() {
        $data = ['test' => true];
        $response = $this->make_api_request('test', $data);
        return $response !== false;
    }
    
    /**
     * 测试许可证是否存在于服务端
     */
    public function test_license_exists($license_key) {
        if (!$this->validate_license_key_format($license_key)) {
            return ['exists' => false, 'message' => '许可证密钥格式无效'];
        }
        
        $domain = home_url();
        $data = [
            'license_key' => $license_key,
            'domain' => $domain
        ];
        
        $response = $this->make_api_request('verify', $data);
        
        if (!$response || !is_array($response)) {
            return ['exists' => false, 'message' => '无法连接到远程服务器'];
        }
        
        // 如果服务端返回success: true，说明许可证存在（不管是否激活）
        return [
            'exists' => $response['success'] === true,
            'status' => $response['status'] ?? 'unknown',
            'message' => $response['message'] ?? '未知状态'
        ];
    }
    
    /**
     * 同步激活状态到所有模块
     */
    public function sync_activation_status() {
        // 获取当前激活状态
        $is_active = $this->is_activated();
        
        // 获取许可证信息
        $license_key = get_option('spider_license_key', '');
        $license_info = null;
        
        if (!empty($license_key)) {
            $license_info = $this->get_license_info();
        }
        
        // 同步到安全模块
        if (function_exists('wp_spider_premium_security')) {
            $security = wp_spider_premium_security();
            $expires_at = null;
            
            // 从API响应中获取过期时间
            if ($license_info && isset($license_info['success']) && $license_info['success']) {
                $expires_at = $license_info['expires_at'] ?? null;
            }
            
            $security->set_premium_status($is_active, $expires_at);
        }
        
        // 同步到许可证验证模块
        if (function_exists('wp_spider_secure_license_verification')) {
            $verification = wp_spider_secure_license_verification();
            if ($is_active && !empty($license_key)) {
                $verification->set_license_key($license_key);
            }
        }
        
        return $is_active;
    }
    
    /**
     * 诊断激活状态问题
     */
    public function diagnose_activation_issues() {
        $issues = [];
        $solutions = [];
        
        // 检查许可证密钥
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            $issues[] = '未找到许可证密钥';
            $solutions[] = '请先激活许可证';
            return [
                'issues' => $issues,
                'solutions' => $solutions,
                'is_active' => false,
                'license_key' => '',
                'activation_data' => []
            ];
        }
        
        // 检查许可证密钥格式
        if (!$this->validate_license_key_format($license_key)) {
            $issues[] = '许可证密钥格式无效';
            $solutions[] = '请检查许可证密钥格式，应为 XXXXX-XXXXX-XXXXX-XXXXX-XXXXX';
            return [
                'issues' => $issues,
                'solutions' => $solutions,
                'is_active' => false,
                'license_key' => $license_key,
                'activation_data' => []
            ];
        }
        
        // 测试许可证是否存在于服务端
        $test_result = $this->test_license_exists($license_key);
        if (!$test_result['exists']) {
            $issues[] = '许可证在服务端不存在：' . $test_result['message'];
            $solutions[] = '请检查许可证密钥是否正确，或联系管理员';
            return [
                'issues' => $issues,
                'solutions' => $solutions,
                'is_active' => false,
                'license_key' => $license_key,
                'activation_data' => [],
                'server_status' => $test_result['status']
            ];
        }
        
        // 检查激活数据
        $activation_data = get_option('spider_license_activation', []);
        if (empty($activation_data)) {
            $issues[] = '未找到激活数据';
            $solutions[] = '请重新激活许可证';
        } elseif (!isset($activation_data['is_active'])) {
            $issues[] = '激活数据格式错误';
            $solutions[] = '请重新激活许可证';
        } elseif (!$activation_data['is_active']) {
            $issues[] = '许可证未激活';
            $solutions[] = '请激活许可证';
        }
        
        // 检查服务端状态
        if (!empty($activation_data['server_status'])) {
            if ($activation_data['server_status'] !== 'active') {
                $issues[] = '服务端状态不是active：' . $activation_data['server_status'];
                $solutions[] = '请重新激活许可证';
            }
        }
        
        // 检查过期状态
        if (!empty($activation_data['expires_at'])) {
            $expires_at = strtotime($activation_data['expires_at']);
            if ($expires_at < current_time('timestamp')) {
                $issues[] = '许可证已过期';
                $solutions[] = '请续费或获取新的许可证';
            }
        }
        
        // 检查安全模块状态
        if (function_exists('wp_spider_premium_security')) {
            $security = wp_spider_premium_security();
            $security_active = $security->is_premium_activated();
            $client_active = $this->is_activated();
            
            if ($security_active !== $client_active) {
                $issues[] = '安全模块与客户端激活状态不一致';
                $solutions[] = '正在同步激活状态...';
                $this->sync_activation_status();
            }
        }
        
        return [
            'issues' => $issues,
            'solutions' => $solutions,
            'is_active' => $this->is_activated(),
            'license_key' => $license_key,
            'activation_data' => $activation_data,
            'server_status' => $test_result['status'] ?? 'unknown'
        ];
    }
    
    /**
     * 修复激活状态
     */
    public function fix_activation_status() {
        // 强制同步所有模块
        $this->sync_activation_status();
        
        // 重新验证许可证
        $license_key = get_option('spider_license_key', '');
        if (!empty($license_key)) {
            $this->verify_license();
        }
        
        return $this->is_activated();
    }
    
    /**
     * 验证许可证密钥格式
     */
    private function validate_license_key_format($license_key) {
        // 许可证密钥格式：XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
        return preg_match('/^[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}$/', $license_key);
    }
    
    /**
     * 清除验证缓存
     */
    private function clear_verification_cache($license_key = null) {
        if ($license_key) {
            $cache_key = 'spider_license_verification_' . md5($license_key);
            delete_transient($cache_key);
        } else {
            // 清除所有验证缓存
            global $wpdb;
            $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_spider_license_verification_%'");
            $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_spider_license_verification_%'");
        }
    }
    
    /**
     * 获取服务端公钥
     */
    private function fetch_server_public_key() {
        // 从远程服务器获取公钥
        $response = wp_remote_get('https://zibovip.top/dingyue/get-public-key.php');
        if (is_wp_error($response)) {
            if ($this->debug) {
                error_log('[SpiderMonitor] Failed to fetch public key: ' . $response->get_error_message());
            }
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body, true);
        
        if ($result && isset($result['public_key'])) {
            // 保存公钥到选项
            update_option('spider_server_public_key', $result['public_key']);
            // 缓存公钥1小时
            set_transient('spider_server_public_key', $result['public_key'], 3600);
            if ($this->debug) {
                error_log('[SpiderMonitor] Public key fetched and saved successfully');
            }
            return true;
        }
        
        if ($this->debug) {
            error_log('[SpiderMonitor] Failed to parse public key response: ' . $body);
        }
        return false;
    }

    /**
     * 公共方法：清除验证缓存
     */
    public function clear_cache() {
        $license_key = get_option('spider_license_key', '');
        $this->clear_verification_cache($license_key);
    }
}
}

// 初始化全局客户端实例
if (!isset($GLOBALS['spider_subscription_client'])) {
    $GLOBALS['spider_subscription_client'] = new Spider_Subscription_Client();
}
?>
